<?php declare(strict_types=1);


namespace PinWuYun\domain\helper;

use Exception;
use PinWuYun\domain\dao\GoodsReleaseDao;
use PinWuYun\domain\dao\GoodsSkuReleaseDao;
use PinWuYun\domain\service\youZanServer\GoodsServer;

/**
 * Created: by zhiJie
 * Date: 2021/7/1
 */
class syncHelper
{
    /**
     * @param $spuId
     * @param $alias
     * @param $itemId
     * @throws Exception
     */
    public static function syncGoodsToDb($spuId, $alias, $itemId)
    {
        /** save to main table */
        GoodsReleaseDao::insert([
            'star_spu_id'=>$spuId,
            'you_alias'=>$alias,
            'you_item_id'=>$itemId,
        ]);
        /** get goods sku list  */
        $detail = (new GoodsServer)->getGoodsDetail($alias);
        // get all sku list
        if($detail['code'] != 200 || !$detail['success']) {
            throw new Exception('获取不到详情：'. $detail['message']);
        }
        $allData = [];
        $data = $detail['data'];
        foreach ($data['spu']['list'] as $index => $item) {
                $allData[$index] = [
                    'item_id' => $itemId,
                    'you_sku_id' => $item['id'],
                    'code' => $item['code'],
                ];
        }
        // insert all
        GoodsSkuReleaseDao::batchInsert($allData);
    }


}